﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer.Manager;
using Common;
using Objects;
using AutoFix.Base;
using System.Text;

namespace AutoFix
{
    public partial class search_article : BasePage
    {
        #region [Private Members]
        /// <summary>
        /// The logged in user
        /// </summary>
        private User applicationUser = null;

        #endregion

        #region [BasePage Implementations]
        /// <summary>
        /// Gets or sets a value indicating whether [is login page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is login page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsLoginPage { get { return false; } }

        /// <summary>
        /// Gets or sets a value indicating whether [is anonymous page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is anonymous page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsAnonymousPage { get { return true; } }

        /// <summary>
        /// Page name
        /// </summary>
        protected override string PageName
        {
            get { return "Search Articles"; }
        }

        /// <summary>
        /// Gets the authorized user types.
        /// </summary>
        protected override List<UserType> AuthorizedUserTypes
        {
            get { return new List<UserType>(new UserType[] { UserType.Admin, UserType.Contributor, UserType.Guest }); }
        }

        #endregion

        #region [Event Handlers]
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            applicationUser = this.PageSession.ApplicationUser;


            this.pageActionMessage.InnerText = "";
            this.pageActionMessage.Attributes.Remove("class");
            if (!(Page.IsPostBack))
            {

            }
        }

        /// <summary>
        /// Handles the click event of the search button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            ArticleManager articleManager = new ArticleManager();
            List<SearchArticle> searchedArticleDetails = null;
            string toggle = @"<script type='text/javascript'>
                                $('#slider-button').click();
                            </script>";
            this.ltrlJS.Text = toggle;

            try
            {
                int vehicleModelId = Convert.ToInt32(this.hdnModelSelectedValue.Value);
                int vehicleModelTypeId = Convert.ToInt32(this.hdnModelTypeSelectedValue.Value);
                int vehicleModelTypeYearId = Convert.ToInt32(this.hdnModelTypeYearSelectedValue.Value);
                string articleName = this.txtSearch.Text.Trim();
                searchedArticleDetails = articleManager.GetArticleByVehicleDetails(vehicleModelId, vehicleModelTypeId, vehicleModelTypeYearId, articleName);
                if (searchedArticleDetails != null && searchedArticleDetails.Count > 0)
                {
                    foreach (SearchArticle articlesByVehicleDetail in searchedArticleDetails)
                    {

                        FillArticleImage(articlesByVehicleDetail);
                        FillArticleType(articlesByVehicleDetail);
                        FillArticleRating(articlesByVehicleDetail);
                        FillArticleUser(articlesByVehicleDetail);
                        if (applicationUser.EmailAddress != AppConfiguration.AnonymousUserName)
                        {
                            if (articlesByVehicleDetail.UserID != applicationUser.UserID)
                            {
                                articlesByVehicleDetail.ReadOnly = false;
                            }
                            else
                            {
                                articlesByVehicleDetail.ReadOnly = true;
                            }
                        }
                        else
                        {
                            articlesByVehicleDetail.ReadOnly = true;
                        }

                    }
                    this.dtlArticles.DataSource = searchedArticleDetails;
                    this.dtlArticles.DataBind();
                }
                else
                {

                    this.dtlArticles.DataSource = searchedArticleDetails;
                    this.dtlArticles.DataBind();
                    this.pageActionMessage.InnerText = "Couldn't find any articles for the given search. Try again";
                    this.pageActionMessage.Attributes.Add("class", "information-msg");
                }

            }
            catch (Exception)
            {
                this.pageActionMessage.InnerText = "Failed to search article for the following criteria";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                articleManager = null;
                searchedArticleDetails = null;
            }
        }
        /// <summary>
        /// Handles the change event of the rating button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void articleRating_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
        {
            string[] ratingInfo = ((AjaxControlToolkit.Rating)sender).BehaviorID.Split(',');

            string currentRatedValue = e.Value;
            RatingManager ratingManager = new RatingManager();
            ArticleRating articleRating = new ArticleRating();
            try
            {
                articleRating.ArticleID = Convert.ToInt32(ratingInfo[0]);
                articleRating.UserID = Convert.ToInt32(ratingInfo[1]);
                articleRating.Rating = Convert.ToInt32(currentRatedValue);
                articleRating.IsActive = true;
                bool success = ratingManager.UpdateRating(articleRating);
                if (success)
                {
                    this.pageActionMessage.InnerText = "The article was successfully rated.";
                    this.pageActionMessage.Attributes.Add("class", "success-msg");
                }
                else
                {
                    this.pageActionMessage.InnerText = "Failed to rate the following article";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }
            }
            catch (Exception)
            {
                this.pageActionMessage.InnerText = "Unable to rate the following article";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                ratingManager = null;
                articleRating = null;
            }

        }
    
       
   
        #endregion       

        #region [Private Methods]
        /// <summary>
        /// Fills the article user information
        /// </summary>
        /// <param name="articlesByVehicleDetail">articlesByVehicleDetail</param>
        private void FillArticleUser(SearchArticle articlesByVehicleDetail)
        {
            UserManager userManager = new UserManager();
            List<GetUserByArticleID> userDetails = null;
            try
            {
                userDetails = userManager.GetUserByArticleID(articlesByVehicleDetail.ArticleID);
                if (userDetails != null && userDetails.Count > 0)
                {
                    articlesByVehicleDetail.UserName = userDetails[0].UserName;
                    articlesByVehicleDetail.UserID = userDetails[0].UserID;
                    if (userDetails[0].ProfilePictureURL == string.Empty)
                    {
                        articlesByVehicleDetail.ProfilePictureURL = "images/imgDefaultProfile.png";
                    }
                    else
                    {
                        articlesByVehicleDetail.ProfilePictureURL = AppConfiguration.UserProfileImagePath + userDetails[0].ProfilePictureURL;
                    }

                }
            }
            catch (Exception)
            {
            }
            finally
            {
                userManager = null;
                userDetails = null;
            }
        }
        /// <summary>
        /// Fills the article rating
        /// </summary>
        /// <param name="articlesByVehicleDetail">articlesByVehicleDetail</param>
        private void FillArticleRating(SearchArticle articlesByVehicleDetail)
        {
            RatingManager articleRatingManager = new RatingManager();
            List<GetArticleRatingByArticleID> articleRatings = null;
            try
            {
                articleRatings = articleRatingManager.GetArticleRatingByArticleID(articlesByVehicleDetail.ArticleID);
                if (articleRatings != null && articleRatings.Count > 0)
                {
                    articlesByVehicleDetail.RatingStars = articleRatings[0].Rating;

                }
            }
            catch (Exception)
            {
            }
            finally
            {
                articleRatingManager = null;
                articleRatings = null;
            }
        }
        /// <summary>
        /// Fills the article type
        /// </summary>
        /// <param name="articlesByVehicleDetail">articlesByVehicleDetail</param>
        private void FillArticleType(SearchArticle articlesByVehicleDetail)
        {
            ArticleTypeManager articleTypeManager = new ArticleTypeManager();
            List<GetArticleTypeByArticleID> articleTypes = null;
            try
            {
                articleTypes = articleTypeManager.GetArticleTypeByArticleID(articlesByVehicleDetail.ArticleID);
                if (articleTypes != null && articleTypes.Count > 0)
                {
                    articlesByVehicleDetail.ArticleTypeName = (articleTypes[0].ArticleTypeID == (int)ArticleEnums.Blog) ? "Blog" : (articleTypes[0].ArticleTypeID == (int)ArticleEnums.Video) ? "Video" : "";

                }
            }
            catch (Exception)
            {
            }
            finally
            {
                articleTypeManager = null;
                articleTypes = null;
            }
        }
        /// <summary>
        /// Fills the article image
        /// </summary>
        /// <param name="articlesByVehicleDetail">the articlesByVehicleDetail</param>
        private void FillArticleImage(SearchArticle articlesByVehicleDetail)
        {
            if (articlesByVehicleDetail.ArticleImageUrl!= string.Empty)
            {
                StringBuilder pathToFile = new StringBuilder();
                pathToFile.Append(AppConfiguration.ArticlePath);
                pathToFile.Append("/");
                pathToFile.Append(articlesByVehicleDetail.ArticleID);
                pathToFile.Append("/");
                pathToFile.Append(articlesByVehicleDetail.ArticleImageUrl);
                articlesByVehicleDetail.ArticleImageUrl = pathToFile.ToString();
                pathToFile = null;
            }
            else
            {
                articlesByVehicleDetail.ArticleImageUrl = "images/imgNoArticleImage.jpg";

            }
        }
        #endregion 

        #region [Web Methods]
        /// <summary>
        /// Gets the model type years
        /// </summary>
        /// <param name="vehicleModelTypeID">vehicleModelTypeID</param>
        /// <returns>serialized model years</returns>
        [WebMethod]
        public static string GetModelTypeYears(string vehicleModelTypeID)
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<string, string>> resultList = new List<KeyValuePair<string, string>>();
            VehicleModelTypeYearManager vehicleModelTypeYearManager = new VehicleModelTypeYearManager();
            List<VehicleModelTypeYear> vehicleModelTypeYears = null;
            string returnedString = string.Empty;

            try
            {
                vehicleModelTypeYears = vehicleModelTypeYearManager.GetVehicleModelTypeYears();
                foreach (VehicleModelTypeYear vehicleModelTypeYear in vehicleModelTypeYears)
                {
                    if (Convert.ToInt16(vehicleModelTypeID) == vehicleModelTypeYear.VehicleModelTypeYearID)
                    {
                        if (vehicleModelTypeYear.IsActive != false)
                        {
                            resultList.Add(new KeyValuePair<string, string>(vehicleModelTypeYear.VehicleModelTypeYearID.ToString(), vehicleModelTypeYear.VehicleYear.ToString()));
                        }

                    }

                }

                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {

            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                vehicleModelTypeYearManager = null;
                vehicleModelTypeYears = null;
            }
            return returnedString;
        }
        /// <summary>
        /// Gets the model types
        /// </summary>
        /// <param name="vehicleModelID">vehicleModelID</param>
        /// <returns>serialized model types</returns>
        [WebMethod]
        public static string GetModelTypes(string vehicleModelID)
        {

            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<string, string>> resultList = new List<KeyValuePair<string, string>>();
            VehicleModelTypeManager vehicleModelTypeManager = new VehicleModelTypeManager();
            List<VehicleModelType> vehicleModelTypes = null;
            string returnedString = string.Empty;
            try
            {
                vehicleModelTypes = vehicleModelTypeManager.GetVehicleModelTypes();
                foreach (VehicleModelType vehicleModelType in vehicleModelTypes)
                {
                    if (Convert.ToInt32(vehicleModelID) == vehicleModelType.VehicleModelID)
                    {
                        if (vehicleModelType.IsActive != false)
                        {
                            resultList.Add(new KeyValuePair<string, string>(vehicleModelType.VehicleModelTypeID.ToString(), vehicleModelType.VehicleModelTypeName));
                        }

                    }

                }

                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {

            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                vehicleModelTypeManager = null;
                vehicleModelTypes = null;
            }
            return returnedString;
        }
        /// <summary>
        /// Gets the vehicle models
        /// </summary>
        /// <returns>serialized models</returns>
        [WebMethod]
        public static string GetAllModels()
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<string, string>> resultList = new List<KeyValuePair<string, string>>();
            VehicleModelManager vehicleModelManager = new VehicleModelManager();
            List<VehicleModel> vehicleModels = null;
            string returnedString = string.Empty;

            try
            {
                vehicleModels = vehicleModelManager.GetVehicleModels();
                foreach (VehicleModel vehicleModel in vehicleModels)
                {
                    if (vehicleModel.IsActive != false)
                    {
                        resultList.Add(new KeyValuePair<string, string>(vehicleModel.VehicleModelID.ToString(), vehicleModel.VehicleModelName));
                    }
                }

                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {

            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                vehicleModelManager = null;
                vehicleModels = null;
            }
            return returnedString;
        }
        /// <summary>
        /// Gets the vehicle model image
        /// </summary>
        /// <returns>serialized model image</returns>
        [WebMethod]
        public static string GetModelImage(string vehicleModelTypeID)
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<int, string>> resultList = new List<KeyValuePair<int, string>>();
            VehicleModelTypeYearManager vehicleModelTypeYearManager = new VehicleModelTypeYearManager();
            List<ModelTypeImage> modelTypeImages = null;
            string returnedString = string.Empty;

            try
            {
                modelTypeImages = vehicleModelTypeYearManager.GetVehicleModelTypeImage(Convert.ToInt32(vehicleModelTypeID));
                if (modelTypeImages[0].VehicleModelTypeImageURL.Contains("imgNoModelImage.png"))
                {
                    resultList.Add(new KeyValuePair<int, string>(0, modelTypeImages[0].VehicleModelTypeImageURL));
                }
                else
                {
                    string folderName = "/" + modelTypeImages[0].VehicleModelTypeImageURL.Substring(0, modelTypeImages[0].VehicleModelTypeImageURL.IndexOf(".jpg")) + "/";
                    resultList.Add(new KeyValuePair<int, string>(0, AppConfiguration.VehicleImagePath + folderName + modelTypeImages[0].VehicleModelTypeImageURL));
                }



                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {

            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                vehicleModelTypeYearManager = null;
                modelTypeImages = null;
            }
            return returnedString;
        }
        #endregion


    }
}